package info.webest.media.activities;

import info.webest.media.AudioVolume;
import info.webest.media.FileItem;
import info.webest.media.MediaMetadata;
import info.webest.media.Options;
import info.webest.media.PlayList;
import info.webest.media.Player;
import info.webest.media.Player.Mode;
import info.webest.media.R;
import info.webest.media.Utilities;
import info.webest.media.activities.fragments.FileManagerFragment;
import info.webest.media.activities.fragments.NavigationDrawerFragment;
import info.webest.media.category.Category;
import info.webest.media.category.Category.StorageType;
import info.webest.media.headset.HeadsetButtonReceiver;
import info.webest.media.headset.HeadsetPlugReceiver;
import info.webest.media.radio.RadioActivity;
import info.webest.media.xml.Bookmark;
import info.webest.media.xml.BookmarkData;
import info.webest.statusbar.Notifications;

import java.io.File;
import java.io.IOException;

import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.ShareActionProvider;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.caverock.androidsvg.SVGImageView;

public class MainActivity extends ActionBarActivity implements
		NavigationDrawerFragment.NavigationDrawerCallbacks,
		ActionBar.OnNavigationListener, OnCompletionListener,
		SeekBar.OnSeekBarChangeListener {

	static MainActivity activity = null;
	// Media Player
	private static MediaPlayer mp;

	HeadsetPlugReceiver headsetPlugReceiver;
	// HeadsetButtonReceiver headsetButtonReceiver;

	ShareActionProvider shareActionProvider = new ShareActionProvider(this);

	int currentVolume;

	int NOTIFY_ID = 1;

	public static PlayList playList;

	PhoneStateListener phoneStateListener;
	// for FORCE_LOCK
	protected static final int REQUEST_ENABLE = 0;
	protected static final int REQUEST_EQUALIZER = 1;

	// for Screen Orientation
	protected static final int REQUEST_PREFERENCE = 1;

	private NavigationDrawerFragment mNavigationDrawerFragment;
	private FragmentManager fragmentManager = getSupportFragmentManager();
	private FileManagerFragment fmFileManager;

	private SVGImageView btnPlay;
	private SVGImageView btnForward;
	private SVGImageView btnBackward;
	private SVGImageView btnNext;
	private SVGImageView btnPrevious;
	// private SVGImageView btnPlaylist;
	private ImageButton btnRepeat;
	private ImageButton btnShuffle;

	private MenuItem btnPlayerMode;

	private SeekBar songProgressBar;
	private TextView songCurrentDurationLabel;
	private TextView songTotalDurationLabel;
	// Handler to update UI timer, progress bar etc,.
	private Handler mHandler = new Handler();
	private Utilities utils;
	private int seekForwardTime = 5000 * 12; // 5000 milliseconds, 5 sec
	private int seekBackwardTime = 5000 * 12; // 5000 milliseconds

	private AudioVolume audioVolume;

	public static MainActivity getInstance() {
		if (activity == null) {
			activity = new MainActivity();
		}
		return activity;
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {

		// setContentView(R.layout.player);
		/*
		 * switch (newConfig.orientation) { case
		 * Configuration.ORIENTATION_LANDSCAPE: break;
		 * 
		 * case Configuration.ORIENTATION_PORTRAIT: break; }
		 */

		super.onConfigurationChanged(newConfig);

	}

	public void restoreActionBar() {
		ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		actionBar.setDisplayShowTitleEnabled(true);
		// actionBar.setTitle(mTitle);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		if (!mNavigationDrawerFragment.isDrawerOpen()) {
			// Only show items in the action bar relevant to this screen
			// if the drawer is not showing. Otherwise, let the drawer
			// decide what to show in the action bar.
			getMenuInflater().inflate(R.menu.main_action_bar, menu);
			// menu.setGroupVisible(R.id.grVolumeControl,
			// Options.VolumeControl);
			restoreActionBar();

			return true;
		}
		return super.onCreateOptionsMenu(menu);
	}

	// Call to update the share intent
	public Intent getShareIntent() {
		// //////////////////////////////////////// to delete
		// //////////////////////////////////

		// populate the share intent with data
		Intent intent = new Intent(Intent.ACTION_SEND);

		// text
		// intent.setType("text/plain");
		// intent.putExtra(Intent.EXTRA_TEXT, playList.getFileName());

		// image
		// intent.setType("image/*");
		// Uri uri = Uri.fromFile(new File(getFilesDir(), "foo.jpg"));
		// intent.putExtra(Intent.EXTRA_STREAM, uri);
		//
		// intent.setType("image/jpeg");
		// intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" +
		// receipt.getPhoto()));

		// audio

		/*
		 * android.support.v4.app.ShareCompat.IntentBuilder ib =
		 * ShareCompat.IntentBuilder .from(this); ib.setType("audio/*"); Intent
		 * intent = ib.getIntent();
		 */
		intent.setType("audio/*");

		File file = new File(playList.getSelFolder() + "/"
				+ playList.getFileName());

		Uri uri = Uri.fromFile(file);
		intent.putExtra(Intent.EXTRA_STREAM, uri);

		// String playStoreLink =
		// "https://play.google.com/store/apps/details?id="
		// + getPackageName();
		// String yourShareText = getResources()
		// .getString(R.string.share_text) + playStoreLink;
		// Intent shareIntent = ShareCompat.IntentBuilder.from(this)
		// .setType("text/plain").setText(yourShareText).getIntent();

		return intent;
	}

	public void setShareData() {
		shareActionProvider.setShareIntent(getShareIntent());
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {

		menu.setGroupVisible(R.id.grVolumeControl, Options.VolumeControl);
		menu.setGroupVisible(R.id.grEqualizer, Options.Equalizer);

		MenuItem item_pref = menu.findItem(R.id.action_pref);
		MenuItem item_radio = menu.findItem(R.id.action_radio);
		MenuItem item_favorite = menu.findItem(R.id.action_favorite);
		MenuItem item_multi_choice = menu.findItem(R.id.action_multi_choice);
		MenuItem item_equalizer = menu.findItem(R.id.action_equalizer);

		if (item_pref != null)
			// Theme
			switch (Options.Theme) {
			case THEME_DARK:
				item_pref.setIcon(R.drawable.ic_action_options_dark);
				item_radio.setIcon(R.drawable.ic_menu_audio_radio_dark);
				item_favorite.setIcon(R.drawable.ic_action_favorite_dark);
				item_multi_choice.setIcon(R.drawable.ic_file_multi_choice_dark);
				item_equalizer.setIcon(R.drawable.ic_action_equalizer_dark);
				break;

			case THEME_LIGHT:
				item_pref.setIcon(R.drawable.ic_action_options);
				item_radio.setIcon(R.drawable.ic_menu_audio_radio);
				item_favorite.setIcon(R.drawable.ic_action_favorite);
				item_multi_choice.setIcon(R.drawable.ic_file_multi_choice);
				item_equalizer.setIcon(R.drawable.ic_action_equalizer);

				break;
			}

		// MenuItem deleteItem = menu.findItem(R.id.item_delete);
		// deleteItem.setVisible(true);

		// MenuItem editItem = menu.findItem(R.id.item_edit);
		// editItem.setVisible(true);

		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		Intent intent = null;

		switch (item.getItemId()) {

		// case android.R.id.home:
		// Toast.makeText(this, "home pressed", Toast.LENGTH_LONG).show();
		// break;

		case R.id.menu_exit:
			finish();
			break;

		case R.id.action_volume_rise:
			audioVolume.rise();
			break;

		case R.id.action_volume_low:
			audioVolume.low();
			break;

		case R.id.action_equalizer:
			intent = new Intent(MainActivity.this, EqualizerActivity.class);

			intent.putExtra("audioSessionId", mp.getAudioSessionId());
			startActivityForResult(intent, REQUEST_EQUALIZER);
			break;

		case R.id.action_multi_choice:
			/*
			 * switch (fmFileManager.lvFileItems.getChoiceMode()) { case
			 * ListView.CHOICE_MODE_SINGLE: fmFileManager.lvFileItems
			 * .setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); break;
			 * 
			 * case ListView.CHOICE_MODE_MULTIPLE: fmFileManager.lvFileItems
			 * .setChoiceMode(ListView.CHOICE_MODE_SINGLE); break; }
			 */
			Options.CHOICE_MODE_MULTIPLE = !Options.CHOICE_MODE_MULTIPLE;
			fmFileManager.Refresh();

			break;

		case R.id.action_radio:
			intent = new Intent(MainActivity.this, RadioActivity.class);
			// intent.putExtra("file", mp.getAudioSessionId());
			// startActivityForResult(intent, REQUEST_EQUALIZER);
			startActivity(intent);
			break;

		case R.id.action_pref:
		case R.id.menu_pref:
			startActivityForResult(new Intent(MainActivity.this,
					PrefActivity.class), NOTIFY_ID);
			break;

		case R.id.menu_help:
		case R.id.menu_about:
			intent = new Intent(MainActivity.this, RadioActivity.class);
			// intent.putExtra("file", mp.getAudioSessionId());
			// startActivityForResult(intent, REQUEST_EQUALIZER);
			startActivity(intent);
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	// @Override
	public void onAttachedToWindow() {

		// int flags = 0;
		// flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
		// flags |= WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
		// flags |= WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
		// flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
		// window.clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
		// this.getWindow().setFlags(flags, flags);
	}

	@Override
	protected void onResume() {
		super.onResume();
		fmFileManager.backToSelFolder();
	}

	// @Override
	// protected void onPause() {
	// super.onPause();
	// }

	// @Override
	// protected void onStart() {
	// super.onStart();
	// }

	@Override
	protected void onStop() {
		super.onStop();

		if (!Options.KeepNotification) {
			Notifications.getInstance(this).clearNotification();
		}

		String folder = playList.getSelFolder();

		if (folder != null) {
			if (playList.selItems.itemIndex != -1) {
				String xml = Bookmark.write(playList.getFileName(),
						mp.getCurrentPosition());
				Bookmark.save(folder, xml);
			}
		}

		/*
		 * //http://stackoverflow.com/questions/8987847/devicepolicymanager-locknow
		 * -is-not-working-for-motorola-tablets DevicePolicyManager
		 * devicePolicyManager; ComponentName adminComponent;
		 * 
		 * adminComponent = new ComponentName(this, DAR.class);
		 * devicePolicyManager = (DevicePolicyManager)
		 * getSystemService(Context.DEVICE_POLICY_SERVICE);
		 * 
		 * if (!devicePolicyManager.isAdminActive(adminComponent)) {
		 * 
		 * Intent intent = new Intent(
		 * DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
		 * intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
		 * adminComponent); startActivityForResult(intent, REQUEST_ENABLE); }
		 * else { devicePolicyManager.lockNow(); }
		 */
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_ENABLE:
			super.onActivityResult(requestCode, resultCode, data);
			break;

		case REQUEST_PREFERENCE:
			InitPreference();
			// boolean RefreshUI = data.getBooleanExtra("RefreshUI", false);
			// if (RefreshUI) {
			// fmFileManager.Refresh();
			// }

			// Refresh menu/actionbar
			ActivityCompat.invalidateOptionsMenu(this);

			fmFileManager.setFastScroll(Options.FastScroll);

			// Theme
			setTheme(Options.getThemeId());

			// HEADSET BUTTON
			HeadsetButtonReceiver.setRegister(Options.HeadsetButton);

			audioVolume.setFlagShowUI(Options.VolumeIndicator);

			break;
		}
	}

	public void stopSong() {
		if (mp.isPlaying()) {
			pause();
		}
	}

	public void InitPreference() {

		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setHomeButtonEnabled(true);

		// Configuration config = getResources().getConfiguration();
		// int orientation = config.orientation;

		switch (Options.Orientation) {

		case SCREEN_PORTRAIT:
			// if (orientation != Configuration.ORIENTATION_PORTRAIT)
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			break;

		case SCREEN_LANDSCAPE:
			// if (orientation != Configuration.ORIENTATION_LANDSCAPE)
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			break;

		default:
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
			break;
		}

		// Options.ShowWhenLocked

		if (Options.ShowWhenLocked) {
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
		} else {
			getWindow().clearFlags(
					WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
		}

		// Options.ShowFileSize, Options.ShowDuration

		// if (fmFileManager != null)
		// fmFileManager.notifyDataSetChanged();
	}

	public void Init() {
		/*
		 * switch (Player.getMode()) { case MODE_AUDIO_MUSIC:
		 * setContentView(R.layout.player); break; case MODE_AUDIO_BOOK:
		 * setContentView(R.layout.player); break; default:
		 * Player.setMode(Player.Mode.MODE_AUDIO_MUSIC);
		 * setContentView(R.layout.player); }
		 */

		setContentView(R.layout.player);

		// All player buttons
		btnPlay = (SVGImageView) findViewById(R.id.btnPlay);
		// btnPlay.setImageAsset("buttons/pause.svg");
		btnPlay.setImageResource(R.drawable.btn_play);

		if (mp.isPlaying()) {
			btnPlay.setImageResource(R.drawable.img_pause);
		} else {
			btnPlay.setImageResource(R.drawable.img_play);
		}

		btnForward = (SVGImageView) findViewById(R.id.btnForward);
		btnBackward = (SVGImageView) findViewById(R.id.btnBackward);

		btnNext = (SVGImageView) findViewById(R.id.btnNext);
		btnNext.setImageResource(R.drawable.img_next);

		btnPrevious = (SVGImageView) findViewById(R.id.btnPrevious);
		// btnPlaylist = (SVGImageView) findViewById(R.id.btnPlaylist);

		btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
		btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);

		songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
		songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
		songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);

		// Listeners
		songProgressBar.setOnSeekBarChangeListener(this); // Important

		/**
		 * Play button click event plays a song and changes button to pause
		 * image pauses a song and changes button to play image
		 * */
		btnPlay.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// check for already playing
				if (mp.isPlaying()) {
					pause();
				} else {
					// Resume song
					resume();
				}

			}
		});

		// Forward button click event Forwards song specified seconds

		btnForward.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// get current song position
				int currentPosition = mp.getCurrentPosition();
				// check if seekForward time is lesser than song duration
				if (currentPosition + seekForwardTime <= mp.getDuration()) {
					// forward song
					mp.seekTo(currentPosition + seekForwardTime);
				} else {
					// forward to end position
					mp.seekTo(mp.getDuration());
				}
			}
		});

		// Backward button click event Backward song to specified seconds
		btnBackward.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// get current song position
				int currentPosition = mp.getCurrentPosition();
				// check if seekBackward time is greater than 0 sec
				if (currentPosition - seekBackwardTime >= 0) {
					// forward song
					mp.seekTo(currentPosition - seekBackwardTime);
				} else {
					// backward to starting position
					mp.seekTo(0);
				}

			}
		});

		/**
		 * Next button click event Plays next song by taking currentSongIndex +
		 * 1
		 * */
		btnNext.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				skip();
			}
		});

		/**
		 * Back button click event Plays previous song by currentSongIndex - 1
		 * */
		btnPrevious.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				playList.autoPrevious();
				playSong(playList.selItems.itemIndex, 0, true);
			}
		});

		/**
		 * Button Click event for Repeat button Enables repeat flag to true
		 * */
		if (playList.isRepeat()) {
			btnRepeat.setImageResource(R.drawable.img_btn_repeat_pressed);
		}
		btnRepeat.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (playList.isRepeat()) {
					// *playList.isRepeat = false;
					playList.setPlayMode(PlayList.PlayMode.MODE_NONE);
					Toast.makeText(getApplicationContext(), "Repeat is OFF",
							Toast.LENGTH_SHORT).show();
					btnRepeat.setImageResource(R.drawable.btn_repeat);
				} else {
					// make repeat to true
					// *playList.isRepeat = true;
					playList.setPlayMode(PlayList.PlayMode.MODE_REPEAT);
					Toast.makeText(getApplicationContext(), "Repeat is ON",
							Toast.LENGTH_SHORT).show();
					// make shuffle to false
					// *playList.isShuffle = false;
					btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
					btnShuffle.setImageResource(R.drawable.btn_shuffle);
				}
			}
		});

		/**
		 * Button Click event for Shuffle button Enables shuffle flag to true
		 * */
		if (playList.isShuffle()) {
			btnShuffle.setImageResource(R.drawable.img_btn_shuffle_pressed);
		}
		btnShuffle.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (playList.isShuffle()) {
					// *playList.isShuffle = false;
					playList.setPlayMode(PlayList.PlayMode.MODE_NONE);
					Toast.makeText(getApplicationContext(), "Shuffle is OFF",
							Toast.LENGTH_SHORT).show();
					btnShuffle.setImageResource(R.drawable.btn_shuffle);
				} else {
					// make repeat to true
					// *playList.isShuffle = true;
					playList.setPlayMode(PlayList.PlayMode.MODE_SHUFFLE);
					Toast.makeText(getApplicationContext(), "Shuffle is ON",
							Toast.LENGTH_SHORT).show();
					// make shuffle to false
					// *playList.isRepeat = false;
					btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
					btnRepeat.setImageResource(R.drawable.btn_repeat);
				}
			}
		});

		/**
		 * Button Click event for Play list click event Launches list activity
		 * which displays list of songs
		 * 
		 * btnPlaylist.setOnClickListener(new View.OnClickListener() {
		 * 
		 * @Override public void onClick(View arg0) { Intent i = new
		 *           Intent(getApplicationContext(), FileManagerFragment.class);
		 *           i.putExtra("path", MEDIA_PATH);
		 * 
		 *           startActivityForResult(i, 100); } });
		 * */

		ChangeMode(Player.getMode());
	}

	public void ChangeMode(Mode mode) {

		Player.setMode(mode);
		int icon_id = 0;

		switch (Player.getMode()) {
		case MODE_AUDIO_MUSIC:
			icon_id = R.drawable.ic_menu_audio_music;
			btnForward.setVisibility(View.GONE);
			btnBackward.setVisibility(View.GONE);
			btnRepeat.setVisibility(View.VISIBLE);
			btnShuffle.setVisibility(View.VISIBLE);
			break;
		case MODE_AUDIO_BOOK:
			icon_id = R.drawable.ic_menu_audio_book;
			btnForward.setVisibility(View.VISIBLE);
			btnBackward.setVisibility(View.VISIBLE);
			btnRepeat.setVisibility(View.GONE);
			btnShuffle.setVisibility(View.GONE);
			break;
		case MODE_AUDIO_RECORDING:
			icon_id = R.drawable.ic_menu_audio_recording;
			btnForward.setVisibility(View.GONE);
			btnBackward.setVisibility(View.GONE);
			btnRepeat.setVisibility(View.VISIBLE);
			btnShuffle.setVisibility(View.VISIBLE);
			break;
		default:
		}
		if (btnPlayerMode != null)
			btnPlayerMode.setIcon(icon_id);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		// Theme
		setTheme(Options.getThemeId());

		super.onCreate(savedInstanceState);

		activity = this;

		// Mediaplayer
		mp = new MediaPlayer();
		mp.setOnCompletionListener(this); // Important

		InitPreference();

		// HEADSET PLUG
		headsetPlugReceiver = new HeadsetPlugReceiver();
		IntentFilter intentFilter = new IntentFilter();
		// intentFilter.addAction(Intent.ACTION_MEDIA_BUTTON);
		intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
		// intentFilter.setPriority(10000);
		this.registerReceiver(headsetPlugReceiver, intentFilter);

		if (Options.HeadsetButton) {
			HeadsetButtonReceiver.setRegister(Options.HeadsetButton);
		}

		// Getting all songs list
		playList = new PlayList(this);

		// Mediaplayer
		mp = new MediaPlayer();
		mp.setOnCompletionListener(this); // Important

		utils = new Utilities();

		phoneStateListenerStart();

		audioVolume = new AudioVolume(this, Options.VolumeIndicator);

		Init();

		// FragmentTransaction ft = fragmentManager.beginTransaction();
		// update the main content by replacing fragments
		fmFileManager = new FileManagerFragment();
		// ft.replace(R.id.container, fmFileManager).commit();

		mNavigationDrawerFragment = (NavigationDrawerFragment) fragmentManager
				.findFragmentById(R.id.navigation_drawer);
		// mTitle = getTitle();

		// Set up the drawer.

		mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
				(DrawerLayout) findViewById(R.id.drawer_layout));

		// show splash screen
		fragmentManager.beginTransaction()
				.replace(R.id.container, fmFileManager).commit();

		// set Progress bar values
		songProgressBar.setProgress(0);
		songProgressBar.setMax(100);

		final Intent intent = getIntent();
		final String action = intent.getAction();

		if (Intent.ACTION_VIEW.equals(action)) {

			Uri uri = intent.getData();
			File f = new File(uri.getPath());
			playSong(f, 0, true);

		} else {
			// Log.d(TAG, "intent was something else: "+action);
			// Toast.makeText(this, "intent was something else: " + action,
			// Toast.LENGTH_SHORT).show();

			String folder = playList.getSelFolder();

			if (folder != null) {
				String xml = Bookmark.load(folder);
				BookmarkData bm = Bookmark.read(xml);
				if (bm.file != null) {
					File f = new File(folder + "/" + bm.file);
					playSong(f, bm.position, false);
				}
			}
		}
	}

	public void skip() {
		playList.autoNext();
		playSong(playList.selItems.itemIndex, 0, true);
	}

	public void toggle() {
		if (mp != null) {
			if (mp.isPlaying()) {
				pause();
			} else {
				resume();
			}
		}
	}

	public void pause() {
		if (mp != null) {
			mp.pause();
			// Changing button image to play button
			// btnPlay.setImageResource(R.drawable.btn_play);
			btnPlay.setImageResource(R.drawable.btn_play);
			btnPlay.setImageResource(R.drawable.img_play);
		}
	}

	public void resume() {
		if (mp != null) {
			mp.start();
			// Changing button image to pause button
			// btnPlay.setImageResource(R.drawable.btn_pause);
			// btnPlay.setImageAsset("buttons/pause.svg");
			btnPlay.setImageResource(R.drawable.btn_pause);
			btnPlay.setImageResource(R.drawable.img_pause);
		}
	}

	public void playSong() {
		if (playList.selItems.itemIndex != -1) {
			playSong(playList.getFile(), 0, true);
		}
	}

	public void playSong(File f, int position, boolean autoStart) {
		Toast.makeText(this, f.getName(), Toast.LENGTH_SHORT).show();
		playList.play(f);
		playSong(playList.selItems.itemIndex, position, autoStart);
	}

	/**
	 * Function to play a song
	 * 
	 * @param songIndex
	 *            - index of song
	 * */
	public void playSong(int songIndex, int position, boolean autoStart) {

		if (!playList.enabled())
			return;

		// ShowNotification();
		// ShowCustomNotification();
		Notifications n = Notifications.getInstance(this);
		// обычное уведомление
		n.createInfoNotification(MainActivity.class,
				getString(R.string.app_name), playList.getTitle(),
				R.drawable.ic_notification);

		fmFileManager.showSelection();

		FileItem song = playList.selItems.all.get(songIndex);
		File f = (File) song.get("file");

		// Play song
		try {
			mp.reset();
			mp.setDataSource(f.getAbsolutePath());
			mp.prepare();

			if (position > 0 && position < mp.getDuration()) {
				mp.seekTo(position);
			}

			if (autoStart) {

				mp.start();

				// Changing Button Image to pause image
				// btnPlay.setImageResource(R.drawable.btn_pause);
				// btnPlay.setImageAsset("buttons/pause.svg");
				btnPlay.setImageResource(R.drawable.btn_pause);
				btnPlay.setImageResource(R.drawable.img_pause);
			}

			// Updating progress bar
			updateProgressBar();

		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Update timer on seekbar
	 * */
	public void updateProgressBar() {
		mHandler.postDelayed(mUpdateTimeTask, 100);
	}

	/**
	 * Background Runnable thread
	 * */
	private Runnable mUpdateTimeTask = new Runnable() {
		public void run() {

			try {
				long totalDuration = mp.getDuration();
				long currentDuration = mp.getCurrentPosition();

				// Displaying Total Duration time
				songTotalDurationLabel.setText(MediaMetadata
						.formatDuration(totalDuration));
				// Displaying time completed playing
				songCurrentDurationLabel.setText(MediaMetadata
						.formatDuration(currentDuration));

				// Updating progress bar
				int progress = (int) (utils.getProgressPercentage(
						currentDuration, totalDuration));
				// Log.d("Progress", ""+progress);
				songProgressBar.setProgress(progress);

				// Running this thread after 100 milliseconds
				mHandler.postDelayed(this, 100);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	/**
	 * 
	 * */
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromTouch) {

	}

	/**
	 * When user starts moving the progress handler
	 * */
	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// remove message Handler from updating progress bar
		mHandler.removeCallbacks(mUpdateTimeTask);
	}

	/**
	 * When user stops moving the progress hanlder
	 * */
	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		mHandler.removeCallbacks(mUpdateTimeTask);
		int totalDuration = mp.getDuration();
		int currentPosition = utils.progressToTimer(seekBar.getProgress(),
				totalDuration);

		// forward or backward to certain seconds
		mp.seekTo(currentPosition);

		// update timer progress again
		updateProgressBar();
	}

	/**
	 * On Song Playing completed if repeat is ON play same song again if shuffle
	 * is ON play random song
	 * */
	@Override
	public void onCompletion(MediaPlayer arg0) {
		playList.autoNext();
		playSong(playList.selItems.itemIndex, 0, true);
	}

	@Override
	public void onDestroy() {
		unregisterReceiver(headsetPlugReceiver);

		mHandler.removeCallbacks(mUpdateTimeTask);
		mp.stop();
		mp.release();
		phoneStateListenerStop();

		super.onDestroy();
	}

	// http://stackoverflow.com/questions/5610464/stopping-starting-music-on-incoming-calls
	private void phoneStateListenerStart() {
		phoneStateListener = new PhoneStateListener() {
			@Override
			public void onCallStateChanged(int state, String incomingNumber) {
				if (state == TelephonyManager.CALL_STATE_RINGING) {
					// Incoming call: Pause music
					pause();
				} else if (state == TelephonyManager.CALL_STATE_IDLE) {
					// Not in call: Play music
				} else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
					// A call is dialing, active or on hold
					pause();
				}
				super.onCallStateChanged(state, incomingNumber);
			}
		};
		TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		if (mgr != null) {
			mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
		}
	}

	private void phoneStateListenerStop() {
		TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		if (mgr != null) {
			mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
		}
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent me) {
		// Call onTouchEvent of SimpleGestureFilter class
		// this.detector.onTouchEvent(me);
		return super.dispatchTouchEvent(me);
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {

		ChangeMode(Mode.fromInteger(itemPosition + 1));
		return true;
	}

	@Override
	public void onNavigationDrawerItemSelected(int position) {
		switch (position) {
		case 0:

			Category.setStorage(StorageType.INTERNAL_STORAGE);
			fmFileManager.browse(Category.getRootFolder());
			break;

		case 1:
			Category.setStorage(StorageType.EXTERNAL_STORAGE);
			fmFileManager.browse(Category.getRootFolder());
			break;

		case 2:
			fmFileManager
					.browse(Category
							.setCategoryFolder(Category.CategoryFolder.FOLDER_IMAGE_PICTURE));
			break;

		case 3:
			fmFileManager
					.browse(Category
							.setCategoryFolder(Category.CategoryFolder.FOLDER_IMAGE_SCREENSHOTE));
			break;

		case 4:
			fmFileManager
					.browse(Category
							.setCategoryFolder(Category.CategoryFolder.FOLDER_IMAGE_CAMERA));
			break;

		case 5:
			fmFileManager
					.browse(Category
							.setCategoryFolder(Category.CategoryFolder.FOLDER_AUDIO_MUSIC));
			ChangeMode(Player.Mode.MODE_AUDIO_MUSIC);
			break;

		case 6:
			Intent intent = new Intent(MainActivity.this, RadioActivity.class);
			startActivity(intent);
			// ChangeMode(Player.Mode.MODE_AUDIO_MUSIC);
			break;

		case 7:
			fmFileManager
					.browse(Category
							.setCategoryFolder(Category.CategoryFolder.FOLDER_AUDIO_BOOK));
			ChangeMode(Player.Mode.MODE_AUDIO_BOOK);
			break;

		case 8:
			fmFileManager
					.browse(Category
							.setCategoryFolder(Category.CategoryFolder.FOLDER_AUDIO_RECORDING));
			ChangeMode(Player.Mode.MODE_AUDIO_RECORDING);
			break;

		case 9:
			fmFileManager
					.browse(Category
							.setCategoryFolder(Category.CategoryFolder.FOLDER_VIDEO_MOVIE));
			break;

		case 10:
			fmFileManager
					.browse(Category
							.setCategoryFolder(Category.CategoryFolder.FOLDER_OTHER_DOWNLOAD));
			break;

		case 11:
			fmFileManager
					.browse(Category
							.setCategoryFolder(Category.CategoryFolder.FOLDER_OTHER_BLUETOOTH));
			break;
		}
	}

	OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
		public void onAudioFocusChange(int focusChange) {
			if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
				// Lower the volume
				audioVolume.setCurrent(3);
			} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
				// Raise it back to normal
				audioVolume.setCurrent(10);
			}
		}
	};

	//
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		int action = event.getAction();
		int keyCode = event.getKeyCode();
		Configuration config = null;

		if (keyCode == KeyEvent.KEYCODE_VOLUME_UP
				|| keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
			config = getResources().getConfiguration();
		}

		switch (keyCode) {

		case KeyEvent.KEYCODE_VOLUME_UP:

			if (config.orientation == Configuration.ORIENTATION_LANDSCAPE
					&& action == KeyEvent.ACTION_UP) {

				skip();

			} else {
				if (action == KeyEvent.ACTION_DOWN) {
					// TODO
					if (Options.VolumeIndicator) {
						return super.dispatchKeyEvent(event);
					} else {
						audioVolume.rise();
					}
				}
			}
			return true;
		case KeyEvent.KEYCODE_VOLUME_DOWN:
			if (config.orientation == Configuration.ORIENTATION_LANDSCAPE
					&& action == KeyEvent.ACTION_UP) {

				playList.autoPrevious();
				playSong(playList.selItems.itemIndex, 0, true);

			} else {
				if (action == KeyEvent.ACTION_DOWN) {
					// TODO
					if (Options.VolumeIndicator) {
						return super.dispatchKeyEvent(event);
					} else {
						audioVolume.low();
					}
				}
			}
			return true;
		default:
			return super.dispatchKeyEvent(event);
		}
	}

}